package com.kgc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kgc.constants.Constants;
import com.kgc.dto.BrandDto;
import com.kgc.dto.ClassifyDto;
import com.kgc.dto.ModelDto;
import com.kgc.mapper.BrandMapper;
import com.kgc.mapper.ClassifyMapper;
import com.kgc.mapper.ModelMapper;
import com.kgc.pojo.Classify;
import com.kgc.service.ClassifyService;
import com.kgc.utils.StringUtil;
import com.kgc.utils.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author zsy
 * @since 2021-08-04
 */
@Slf4j
@Service
public class ClassifyServiceImpl extends ServiceImpl<ClassifyMapper, Classify> implements ClassifyService {

    @Autowired
    private ClassifyMapper classifyMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public List<ClassifyDto> findClassifyTree() {

        List<ClassifyDto> list=null;

        String value = redisUtils.getValue(Constants.Redis.KEY_HOME_TREE);
        if (StringUtils.isBlank(value)){
            //查询所有商品类型
             list = classifyMapper.findClassifyTree();
            log.info("哥你别搞我：",list);
            //查询所有商品类型下的品牌
            if (list != null){
                for (ClassifyDto classifyDto : list) {
                    Long id = classifyDto.getId();
                    List<BrandDto> brandList = brandMapper.findBrandListById(id);
                    log.info("出来啊：",brandList);
                    //根据品牌id和商品类型id查询商品
                    if (brandList != null){
                        for (BrandDto dto : brandList) {
                            Long id1 = dto.getId();
                            List<ModelDto> modelList = modelMapper.findModelListById(id, id1);
                            dto.setModelList(modelList);
                        }
                    }
                    classifyDto.setBrandList(brandList);
                }
            }
            // 将list转成json
            String json = JSON.toJSONString(list);
            // 将list存入redis
            redisUtils.putValue(Constants.Redis.KEY_HOME_TREE, json);
        } else {
            // 1.1 有数据 直接返回 第一个参数是redis中返回的数据 第二个参数是List的泛型
            list = JSON.parseArray(value, ClassifyDto.class);
        }
        log.info("最终的数据：{}",list);
        return list;
    }
}
